Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example,

Given

  1. 1
  2. / \
  3. 2 5
  4. / \ \
  5. 3 4 6

The flattened tree should look like:

  1. 1
  2. \
  3. 2
  4. \
  5. 3
  6. \
  7. 4
  8. \
  9. 5
  10. \
  11. 6

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public void flatten(TreeNode root) {
  12. if (root == null)
  13. return;
  14. Stack<TreeNode> stack = new Stack<>();
  15. stack.push(root);
  16. TreeNode last = null;
  17. while (!stack.isEmpty()) {
  18. TreeNode curr = stack.pop();
  19. if (last != null) {
  20. last.left = null;
  21. last.right = curr;
  22. }
  23. if (curr.right != null)
  24. stack.push(curr.right);
  25. if (curr.left != null)
  26. stack.push(curr.left);
  27. last = curr;
  28. }
  29. }
  30. }